﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Telerik.Windows.Controls;
using DunSilverlight.Comm;
using DunSilverlight.ViewModel;

namespace DunSilverlight.Views
{
    public partial class RolePanel : Page
    {
        
        RoleService.RoleServiceClient roleSer = new RoleService.RoleServiceClient();
        RightService.RightServiceClient rightSer = new RightService.RightServiceClient();
        public RolePanel()
        {
            if (!RightManagement.VerifyRight(RightManagement.Right_Right_Add))
            {
                if (AppGlobal.CurrentUser != null)
                    Tools.ShowMessage("该用户没有权限查看 ", "", false);
                return;
            }
            InitializeComponent();

            roleSer.GetRolesCompleted += new EventHandler<RoleService.GetRolesCompletedEventArgs>(roleSer_GetRolesCompleted);
            roleSer.GetRightsCompleted += new EventHandler<RoleService.GetRightsCompletedEventArgs>(roleSer_GetRightsCompleted);
            roleSer.DeleteByIdCompleted += new EventHandler<RoleService.DeleteByIdCompletedEventArgs>(roleSer_DeleteByIdCompleted);
            roleSer.SaveOrUpdateCompleted += new EventHandler<RoleService.SaveOrUpdateCompletedEventArgs>(roleSer_SaveOrUpdateCompleted);
            roleSer.CanDeleteCompleted += new EventHandler<RoleService.CanDeleteCompletedEventArgs>(roleSer_CanDeleteCompleted);
            
            this.Loaded += new RoutedEventHandler(RolePanel_Loaded);

        }
       

        void RolePanel_Loaded(object sender, RoutedEventArgs e)
        {
            roleSer.GetRolesAsync();

        }
      
        
        /// <summary>
        /// 加在所有角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void roleSer_GetRolesCompleted(object sender, RoleService.GetRolesCompletedEventArgs e)
        {
            int total = 0;
            IList<DunLibrary.User.Role> cases = JsonSerializerHelper.JsonToEntities<DunLibrary.User.Role>(e.Result, out total);

            RadTreeView1.ItemsSource = cases;
            if (RadTreeView1.Items.Count > 0)
                RadTreeView1.SelectedItem = RadTreeView1.Items[0];
        }


        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 角色选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadTreeView1_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var role = e.AddedItems[0] as DunLibrary.User.Role;

                roleSer.GetRightsAsync(role.Id,role);

                userInfo.DataContext = RoleModel.Create(role);

                
            }
        }

        /// <summary>
        /// 加载角色的权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void roleSer_GetRightsCompleted(object sender, RoleService.GetRightsCompletedEventArgs e)
        {

            int totalCount;
            var entityList = JsonSerializerHelper.JsonToEntities<DunLibrary.User.Right>(e.Result, out totalCount);

            var role = e.UserState as DunLibrary.User.Role;
            if (role != null)
                role.Rights = entityList;

            IList<RightModel> modelList = new List<RightModel>();
            foreach (var item in entityList)
            {
                modelList.Add(RightModel.Create(item));
            }

            RightGrid.ItemsSource = modelList;

            if (RightGrid.Items.Count > 0)
            {
                RightGrid.SelectedIndex = 0;

            }

            
        }

        /// <summary>
        /// 权限列表选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RightGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
           
        }

        /// <summary>
        /// 刷新权限list
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Refresh1_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.SelectedItem != null)
            {
                var role = RadTreeView1.SelectedItem as DunLibrary.User.Role;


                roleSer.GetRightsAsync(role.Id,role);
            }
        }

        /// <summary>
        /// 新建权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add1_Click(object sender, RoutedEventArgs e)
        {
            RightForm form = new RightForm();
            Tools.OpenWindow("新建权限", form, null, new Action(() =>
            {

                //if (RadTreeView1.SelectedItem != null)
                //{
                //    rightSer.GetListByHQLAsync("From Right");
                //}
            }));
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void del1_Click(object sender, RoutedEventArgs e)
        {

            if (RightGrid.Items.Count > 0 && RightGrid.SelectedItem != null)
            {
                RightModel obj = (RightGrid.SelectedItem as RightModel);
                
                EventHandler<WindowClosedEventArgs> callback = new EventHandler<WindowClosedEventArgs>(
                    (o, args) => { if (args.DialogResult == true) roleSer.DeleteByIdAsync(obj.Id); });
                Tools.OpenConfirm("确定要删除吗?", callback);
            }
        }

        void roleSer_DeleteByIdCompleted(object sender, RoleService.DeleteByIdCompletedEventArgs e)
        {
            roleSer.GetRolesAsync();
        }

        /// <summary>
        /// 绑定角色和权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BindRight_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.SelectedItem == null)
            {
                Tools.ShowMessage("请选择角色", "", false);

            }
            else
            {
                var role = RadTreeView1.SelectedItem as DunLibrary.User.Role;
                IList<RightModel> modelList = RightGrid.ItemsSource as IList<RightModel>;

                RightBindForm form = new RightBindForm(role.Id, modelList);
                Tools.OpenWindow("分配权限", form, null,new Action(() =>
                {
                    
                    roleSer.GetRightsAsync(role.Id,role);

                }));
            }
        }

        /// <summary>
        /// 保存角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            var role = (userInfo.DataContext as RoleModel).ToEntity();
            var oldRole = RadTreeView1.SelectedItem as DunLibrary.User.Role;
            if (oldRole != null)
            {
                role.Rights = oldRole.Rights;
                roleSer.SaveOrUpdateAsync(JsonSerializerHelper.EntityToJson(role));
            }
        }


        void roleSer_SaveOrUpdateCompleted(object sender, RoleService.SaveOrUpdateCompletedEventArgs e)
        {
            roleSer.GetRolesAsync();
        }

        /// <summary>
        /// 保存角色的权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddRight_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.SelectedItem == null)
            {
                Tools.ShowMessage("请选择角色", "", false);

            }
            else
            {
                List<RightModel> modelList = RightGrid.ItemsSource as List<RightModel>;
                var list = modelList.Where(c => c.IsInRole == true).Select(c => c.Id);
                string ids = string.Join(",", list);
                var role = RadTreeView1.SelectedItem as DunLibrary.User.Role;
                roleSer.AddRightsAsync(role.Id, ids);
            }
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void del_Click(object sender, RoutedEventArgs e)
        {
            if (RadTreeView1.SelectedItem == null)
            {
                Tools.ShowMessage("请选择一个角色！", "", false);
                return;
            }
            DunLibrary.User.Role role = (RadTreeView1.SelectedItem as DunLibrary.User.Role);
            roleSer.CanDeleteAsync(role.Id);
        }

        void roleSer_CanDeleteCompleted(object sender, RoleService.CanDeleteCompletedEventArgs e)
        {
            if (e.Result == false)
            {
                Tools.ShowMessage("该角色具有关联，不能被删除！", "请删除关联该角色的用户或者将这些用户更改角色！", false);
                return;
            }
            else
            {
                if (RadTreeView1.Items.Count > 0 && RadTreeView1.SelectedItem != null)
                {
                    DunLibrary.User.Role role = (RadTreeView1.SelectedItem as DunLibrary.User.Role);
                    EventHandler<WindowClosedEventArgs> callback = new EventHandler<WindowClosedEventArgs>(
                        (o, args) => { if (args.DialogResult == true) roleSer.DeleteByIdAsync(role.Id); });
                    Tools.OpenConfirm("确定要删除吗?", callback);
                }
            }
        }

        /// <summary>
        /// 新建角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            RoleForm form = new RoleForm();
            Tools.OpenWindow("新建角色", form, null,  new Action(() =>
            {

                roleSer.GetRolesAsync();
            }));
        }

        /// <summary>
        /// 刷新角色列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            roleSer.GetRolesAsync();
        }

    }
}
